local skel = fk.CreateSkill {
  name = "rmt__huabian",
}

skel:addEffect(fk.EventPhaseStart, {
  anim_type = "offensive",
  times = function (_, player)
    return 1 - player:usedSkillTimes(skel.name, Player.HistoryRound)
  end,
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(skel.name) then
      return target.phase == Player.Play and #player:getPile("$rmt__star") > 0 and player:usedSkillTimes(skel.name, Player.HistoryRound) == 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    local use = player.room:askToUseRealCard(player, {
      pattern = ".|.|.|$rmt__star", skill_name = skel.name, cancelable = true, skip = true,
      extra_data = {expand_pile = "$rmt__star", bypass_distances = true},
      prompt = "#rmt__huabian-invoke:"..target.id,
    })
    if use then
      event:setCostData(self, {tos = {target}, skill_info = use})
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:useCard(event:getCostData(self).skill_info)
    if not player.dead and not target.dead then
      local choice = room:askToChoice(player, {
        skill_name = skel.name,
        choices = {"rmt__huabian_draw:"..target.id, "rmt__huabian_discard:"..target.id}
      })
      if choice:startsWith("rmt__huabian_draw") then
        target:drawCards(1, skel.name)
      elseif not target:isNude() then
        room:askToDiscard(target, {
          max_num = 1, min_num = 1, include_equip = true, cancelable = false, skill_name = skel.name,
        })
      end
    end
  end,
})

-- 获得死亡角色的弃牌
skel:addEffect(fk.AfterCardsMove, {
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(skel.name) and player:usedSkillTimes(skel.name) > 0 then
      local e = player.room.logic:getCurrentEvent().parent
      if e and e.event == GameEvent.Death then
        local cards = {}
        for _, move in ipairs(data) do
          if move.moveReason == fk.ReasonDiscard and move.from and move.from.dead then
            for _, info in ipairs(move.moveInfo) do
              table.insertIfNeed(cards, info.cardId)
            end
          end
        end
        if #cards > 0 then
          event:setCostData(self, {cards = cards})
          return true
        end
      end
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    player.room:delay(600)
    player:addToPile("$rmt__star", event:getCostData(self).cards, true, skel.name)
  end,
})

Fk:loadTranslationTable{
  ["rmt__huabian"] = "猾变",
  [":rmt__huabian"] = "每轮限一次，一名角色的出牌阶段开始时，你可无视距离使用一张“星”，令其摸或弃一张牌；发动过“猾变”的回合内，你将已死亡角色的弃牌置入“星”中。",
  ["#rmt__huabian-invoke"] = "猾变：你可以使用一张“星”，然后令 %src 摸或弃1张牌",
  ["rmt__huabian_discard"] = "令 %src 弃1张牌",
  ["rmt__huabian_draw"] = "令 %src 摸1张牌",

  ["$rmt__huabian1"] = "天高高，风肃肃。正合杀人、毋封刀匕。",
  ["$rmt__huabian2"] = "快哉风，直星斗。今夜行兵，尽洗街市！",
}

return skel
